package com.fzf.org.test;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@RestController
public class RedisTestController {

    private final StringRedisTemplate stringRedisTemplate;

    @GetMapping("/hello")
    public String sayHi() {
        System.out.println("hello");
        return "hello";
    }

    @GetMapping("/incr")
    public String incr(@RequestParam("key") String key) {
        System.out.println("incr");
        Long counter = stringRedisTemplate.opsForValue().increment(key);
        if(counter == 1L) {
            stringRedisTemplate.expire(key, 31, TimeUnit.SECONDS);
        }
        System.out.println(counter);
        return "hello~~~" + key + "~~~" + counter;
    }

    @GetMapping("/get")
    public String get(@RequestParam("key") String key) {
        System.out.println("get");
        String cnt = stringRedisTemplate.opsForValue().get(key);
        System.out.println(cnt == null);
        System.out.println(cnt);
        return "hello~~~" + key + "~~~" + (null == cnt ? 0 : Long.parseLong(cnt));
    }


    @GetMapping("/add")
    public String addOrUpdateScore(@RequestParam("key") String key,
                                 @RequestParam("score") double score,
                                 @RequestParam("value") String value) {
        System.out.println("add");
        stringRedisTemplate.opsForZSet().add(key, value, System.currentTimeMillis());
        return "hello2";
    }


    @GetMapping("/remove")
    public String removeByScoreRange(@RequestParam("key") String key,
                                   @RequestParam("min") double min,
                                   @RequestParam("max") double max) {
        System.out.println("remove");
        stringRedisTemplate.opsForZSet().removeRangeByScore(key, min, max);

        return "hello3";
    }


    @GetMapping("/exist")
    public Boolean existkey(@RequestParam("key") String key,
                                     @RequestParam("value") String value) {
        System.out.println("exist");
        return stringRedisTemplate.opsForZSet().score(key, value) != null;
    }


}
